package cn.itcast.bos.web.action;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.AreaService;
import cn.itcast.bos.utils.PinYin4jUtils;
import cn.itcast.bos.web.action.common.BaseAction;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Think on 2017/9/17.
 *
 */
@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope(value = "prototype")
public class AreaAction extends BaseAction<Area> {

    @Autowired
    private AreaService areaService;

    // 上传的文件
    private File file;
    // 上传的文件名
    private String fileFileName;
    // 上传的文件类型
    private String fileContentType;

    public void setFile(File file) {
        this.file = file;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    public void setFileContentType(String fileContentType) {
        this.fileContentType = fileContentType;
    }

    @Action(value = "area_import",results = {@Result(name = SUCCESS,type = "json")})
    public String save() throws IOException {
//        System.out.println(file);
//        System.out.println(fileFileName);
//        System.out.println(fileContentType);
        List<Area> areaList = new ArrayList<Area>();
        // 使用POI技术完成数据导入
        // 核心对象（WorkBook）
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
        //通过workbook获取指定sheet(工作表)
        HSSFSheet sheet = hssfWorkbook.getSheetAt(0);//0表示第一个工作表
        // 通过工作表，获取excel中的行（Row）和单元格（Cell）
        for (Row row : sheet) {
            if(row.getRowNum()==0){
                //第一行是字段,不是数据,不写入数据库,跳过
                continue;
            }
            // 如果第一个单元格的值是null，此时不能导入（缺失主键）
            if(row.getCell(0)==null || StringUtils.isBlank(row.getCell(0).getStringCellValue())){
                continue;
            }
            //开始导入
            Area area = new Area();
            area.setId(row.getCell(0).getStringCellValue());// 将excel的值赋值到Area中
            area.setProvince(row.getCell(1).getStringCellValue());// 将excel的值赋值到Area中
            area.setCity(row.getCell(2).getStringCellValue());// 将excel的值赋值到Area中
            area.setDistrict(row.getCell(3).getStringCellValue());// 将excel的值赋值到Area中
            area.setPostcode(row.getCell(4).getStringCellValue());// 将excel的值赋值到Area中
            // 使用pinyin4j的技术，将省市区，生成简码和城市编码
            String province = area.getProvince().substring(0,area.getProvince().length()-1);//去掉省字
            String city = area.getCity().substring(0, area.getCity().length() - 1);
            String district = area.getDistrict().substring(0, area.getDistrict().length() - 1);
            String[] headByString = PinYin4jUtils.getHeadByString(province + "" + city + "" + district);
            StringBuffer buffer = new StringBuffer();
            for (String head : headByString) {
                buffer.append(head);
            }
            //简码
            String shortcode = buffer.toString();
            area.setShortcode(shortcode);
            //城市的编码
            String citycode = PinYin4jUtils.hanziToPinyin(city,"");
            area.setCitycode(citycode);
            areaList.add(area);
        }
        //调用service层导入
        areaService.saveList(areaList);
        return SUCCESS;
    }



    @Action(value = "area_pageQuery",results = {@Result(name = SUCCESS,type = "json")})
    public String pageQuery(){
        // 调用业务层 ，查询数据结果
        Pageable pageable = new PageRequest(page - 1, rows);

        /**带条件的查询*/
        Specification<Area> specification = new Specification<Area>() {

            @Override
            // Root 用于获取属性字段，CriteriaQuery可以用于简单条件查询，CriteriaBuilder 用于构造复杂条件查询（多表）
            public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate predicate = null;
                List<Predicate> list = new ArrayList<Predicate>();
                if (StringUtils.isNoneBlank(model.getProvince())) {
                    Predicate p1 = cb.like(root.get("province").as(String.class), "%" + model.getProvince() + "%");
                    list.add(p1);
                }
                if (StringUtils.isNoneBlank(model.getCity())) {
                    Predicate p2 = cb.like(root.get("city").as(String.class),"%" + model.getCity() + "%");
                    list.add(p2);
                }
                if (StringUtils.isNoneBlank(model.getDistrict())) {
                    Predicate p3 = cb.like(root.get("district").as(String.class), "%" + model.getDistrict() + "%");
                    list.add(p3);
                }
                if(list!=null && list.size()>0){
                    Predicate [] p = new Predicate[list.size()];
                    predicate = cb.and(list.toArray(p));
                }
                return predicate;
            }
        };
        //带有条件的查询
        Page<Area> pageData = areaService.findPageData(specification,pageable);
        pushPageDataToValueStack(pageData);
        return SUCCESS;
    }


}
